#include <iostream>
#include "sockdist.h"
#include "sock.h"
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include<string>
#include "stdio.h"
#include <cstdlib>
#include <string.h>
using namespace std;

#include "ClientTCP.h"


ClientTCP::ClientTCP(){
}

ClientTCP::ClientTCP(string h,int p,int t,ActionListenner* l):Hote(p,t,l){

  	// Demande de BR local
  	Sock brcli(SOCK_STREAM,0);

  	// On recupere le descripteur
  	if(brcli.good()){
    	Hote::descBrLocale=brcli.getsDesc();

    	cout << "# Demande de BR locale : OK" << endl;
  	}

  	else {
    	cout << "# Erreur : Probleme BR Locale" << endl;
    	exit(1);
  	} 

  	// Designation de la BR distante.
  	hostnameDistant = h;
  	SockDist brPub(Hote::conversionStringChar(hostnameDistant),(short)Hote::port);
  	adrBrDistante = brPub.getAdrDist();
  	lgBrDistante = brPub.getsLen();

}


void ClientTCP::connexion(){
  	//connect
    cout << "# Demande de connexion ..." << endl; 

    int connection = connect(Hote::descBrLocale,(struct sockaddr *)adrBrDistante,(int)lgBrDistante);

  	if(connection == -1){
    	perror("# Connect");
    	exit(EXIT_FAILURE);
  	}
  	else{
    	cout<<"# Connexion Etablie"<<endl;
  	}

}

void ClientTCP::deconnexion(){
	close(this->descBrLocale);
	exit(0);
}

void ClientTCP::envoyer(string t){
	//envoie
 	tamponSnd = conversionStringChar(t);

 	int retourSend = send(Hote::descBrLocale,tamponSnd,Hote::tailleTampon,0);

  	if (retourSend == -1){
    	perror("#  Send");
    	exit(EXIT_FAILURE);
  	}	
  	else if(retourSend == 0){
    	perror("# Circuit virtuel coupe : send");
    	exit(EXIT_FAILURE);
  	}
  	else {
    	//cout<<"# Message envoye"<<endl;
  	}

}

string ClientTCP::recevoir (){

  	int retourRecv = recv(Hote::descBrLocale,tamponRcv,Hote::tailleTampon,0 );

  	if (retourRecv == -1){
    	perror("# Recv ");
    	close(descBrLocale);
		return "#1";
  	}

  	else if(retourRecv == 0){
    	perror("# Circuit virtuel coupe : Recv");
    	close(descBrLocale);
		return "#0";
  	}

  	else{
    	int taille = conversionCharString(tamponRcv).length();
    	//cout<<conversionCharString(tamponRcv).substr(1,taille)<<endl;
    	return conversionCharString(tamponRcv);
  	}

}

void ClientTCP::protocoleDeCommunication(){
	bool exit = false;
	while(!exit){
		string msg = this->recevoir();
		if(msg == "#0")
			exit = true;
		else if(msg != "#1")
			this->listenner->action(0,msg,0);
	}
}
